<?php
/**
 * 物料仓库处理Lib
 * @author ExBOY
 * @version 1.0
 */

class ome_branch_product
{
     var $export_name = '仓库库存';
      function __construct()
     {
         $this->db    = kernel::database();
     }
     
    /*
     * 增加冻结库存
     */
    function freez($branch_id,$product_id,$nums)
    {
        //暂时没有在branch_product上使用冻结库存
        $this->chg_product_store_freeze($branch_id, $product_id, $nums, "+");
        return true;
    }
    
    /*
     * 释放冻结库存
    */
    function unfreez($branch_id,$product_id,$nums)
    {
        //暂时没有在branch_product上使用冻结库存
        return $this->chg_product_store_freeze($branch_id, $product_id, $nums, "-");
    }
     
    /*
     * 修改冻结库存
     */
    function chg_product_store_freeze($branch_id, $product_id, $num, $operator='=', $log_type='delivery')
    {
        $basicMaterialSelect    = kernel::single('material_basic_select');
        
        $now = time();
        $store_freeze = "";
        $mark_no = uniqid();
        
        switch($operator)
        {
            case "+":
                $store_freeze = "store_freeze=IFNULL(store_freeze,0)+".$num.",";
                $action = '增加';
                break;
            case "-":
                $store_freeze = " store_freeze=IF((CAST(store_freeze AS SIGNED)-$num)>0,store_freeze-$num,0),";
                $action = '扣减';
                break;
            case "=":
            default:
                $store_freeze = "store_freeze=".$num.",";
                $action = '覆盖';
                break;
        }
        
        #基础物料
        $product_info    = $basicMaterialSelect->dump('bm_id, material_bn', array('bm_id'=>$product_id));
        
        #仓库库存
        $sql           = 'select store_freeze from '. DB_PREFIX .'ome_branch_product where product_id ='.$product_id.' AND branch_id = '.$branch_id;
        $lastinfo      = $this->db->selectrow($sql);
        
        $sql           = 'select name from '. DB_PREFIX .'ome_branch where branch_id = '.$branch_id;
        $branchinfo    = $this->db->selectrow($sql);
        
        #更新仓库库存
        $sql    = 'UPDATE '. DB_PREFIX .'ome_branch_product SET '.$store_freeze.'last_modified='.$now.' WHERE product_id='.$product_id.' AND branch_id = '.$branch_id;
        $rs = $this->db->exec($sql);
        
        #获取库存
        $sql            = 'select store_freeze from '. DB_PREFIX .'ome_branch_product where product_id ='.$product_id.' AND branch_id = '.$branch_id;
        $currentinfo    = $this->db->selectrow($sql);
        
        #日志
        $log = array(
                'log_type'=>$log_type,
                'mark_no'=>$mark_no,
                'oper_time'=>$now,
                'product_id'=>$product_id,
                'goods_id'=>$product_info['product_id'],//基础物料没有goods_id
                'bn'=>$product_info['bn'],
                'branch_id'=>$branch_id,
                'branch_name'=>$branchinfo['name'],
                'stock_action_type'=>$action,
                'last_num'=>$lastinfo['store_freeze'],
                'change_num'=>$num,
                'current_num'=>$currentinfo['store_freeze'],
        );
        
        kernel::single('ome_freeze_stock_log')->changeLog($log);

        return $rs;
    }
    
    /*
     * 更新仓库库存
    */
    function change_store($branch_id, $product_id, $num, $operator='=', $update_material=true)
    {
        $now = time();
        $store = '';
        switch($operator){
            case "+":
                $store = "store=IFNULL(store,0)+".$num;
                break;
            case "-":
                $store = " store=IF((CAST(store AS SIGNED)-$num)>0,store-$num,0) ";
                break;
            case "=":
            default:
                $store = "store=".$num;
                break;
        }
    
        $sql    = "UPDATE ".DB_PREFIX."ome_branch_product SET ".$store.",last_modified=".$now." 
                   WHERE product_id=".$product_id." AND branch_id=".$branch_id;
        $result    = $this->db->exec($sql);
        
        if($result)
        {
            if($update_material == false)
            {
                return true;#不统计基础物料库存
            }
            
            return $this->count_store($product_id);
        }
        else
        {
            return false;
        }
    }
    
    /*
     * 统计所有此基础物料库存
    */
    function count_store($product_id, $branch_id=0)
    {
        $mStock    = app::get('material')->model('basic_material_stock');
        
        $time    = time();
        
        $sql     = "SELECT product_id, SUM(store) AS 'store' FROM ".DB_PREFIX."ome_branch_product WHERE product_id='".$product_id."' GROUP BY product_id";
        $row     = $this->db->selectrow($sql);
        if(!$row)
        {
            $data = array(
                    'bm_id' => $product_id,
                    'store' => 0
            );
        }
        else
        {
            $data = array(
                    'bm_id' => $row['product_id'],
                    'store' => $row['store']
            );
        }
        $data['last_modified']            = $time;
        $data['real_store_lastmodify']    = $time;
        $data['max_store_lastmodify']     = $time;
        
        #[更新]基础物料库存
        $mStock->save($data);
        
        return true;
    }
    
    #获取基础物料对应仓库库存
    function getStoreByBranch($product_id, $branch_id)
    {
        $sql    = 'select store from '. DB_PREFIX .'ome_branch_product where product_id='.$product_id.' and branch_id='.$branch_id;
        $row    = $this->db->selectRow($sql);
        
        if($row)
        {
            return $row['store'];
        }
        else 
        {
            return false;
        }
    }
    
    #获取单仓库-多个基础物料仓库
    function getStoreListByBranch($branch_id, $product_ids)
    {
        $sql    = 'select product_id,store from '. DB_PREFIX .'ome_branch_product where product_id in('.implode(',', $product_ids).') and branch_id='.$branch_id;
        $rows   = $this->db->select($sql);
        
        if($rows)
        {
            $products = array();
            foreach($rows as $row)
            {
                $products[$row['product_id']] = $row['store'];
            }
            
            return $products;
        }
        else 
        {
            return false;
        }
    }
    
    #获取单仓库-多个基础物料的可用库存
    function getAvailableStore($branch_id, $product_ids)
    {
        $sql    = 'select product_id,store,store_freeze from '. DB_PREFIX .'ome_branch_product where product_id in('.implode(',', $product_ids).') and branch_id='.$branch_id;
        $rows   = $this->db->select($sql);
        
        if($rows)
        {
            $products = array();
            foreach($rows as $row)
            {
                $products[$row['product_id']] = $row['store'] - $row['store_freeze'];
            }
    
            return $products;
        }
        else 
        {
            return false;
        }
    }
    
    #获取单仓库-单个基础物料中的可用库存
    function get_available_store($branch_id, $product_id)
    {
        $bpModel   = app::get('ome')->model('branch_product');
        $branch    = $bpModel->getList('store, store_freeze',array('product_id'=>$product_id,'branch_id'=>$branch_id), 0, 1);
    
        return $branch[0]['store'] - $branch[0]['store_freeze'];
    }
    
    #查询对应库存总数
    function countBranchProduct($product_id, $column='safe_store')
    {
        $sql    = "SELECT SUM($column) AS 'total' FROM ". DB_PREFIX ."ome_branch_product WHERE product_id = $product_id ";
        $count  = $this->db->selectrow($sql);
        
        return $count['total'];
    }
    
    /**
     * 初始化库存数量为NULL的货品
     */
    public function initNullStore($product_id, $branch_id)
    {
        if($product_id)
        {
            if($branch_id) {
                $sql = "UPDATE ". DB_PREFIX ."ome_branch_product SET store=0 WHERE branch_id='" . $branch_id . "' AND product_id='" . $product_id ."' AND ISNULL(store) LIMIT 1";
            }else{
                $sql = "UPDATE ". DB_PREFIX ."ome_branch_product SET store=0 WHERE product_id='" . $product_id ."' AND ISNULL(store) LIMIT 1";
            }
            
            return $this->db->exec($sql);
        }
        else
        {
            return false;
        }
    }
    
    /*------------------------------------------------------ */
    //-- 以下是不常用方法
    /*------------------------------------------------------ */
    /* 减仓库表库存
     * 备注：货位库存相关方法，可以删除此方法
    * \app\purchase\model\returned\purchase.php 中使用
    */
    function Cut_store($adata)
    {
        $libBranchProductPos    = kernel::single('ome_branch_product_pos');#基础物料 ExBOY
        
        foreach($adata['items'] as $k=>$v)
        {
            $libBranchProductPos->change_store($adata['branch_id'],$v['product_id'],$v['pos_id'],$v['num'],'-');
        }
    }
    
    /*
     * 备注：货位库存相关方法，可以删除此方法
    * \app\purchase\model\appropriation.php 中使用
    */
    function operate_store($adata,$operate)
    {
        $libBranchProductPos    = kernel::single('ome_branch_product_pos');#基础物料 ExBOY
    
        if($operate=='add')
        {
            $libBranchProductPos->change_store($adata['branch_id'],$adata['product_id'],$adata['pos_id'],$adata['num'],'+');
        }
        else if($operate=='lower')
        {
            $libBranchProductPos->change_store($adata['branch_id'],$adata['product_id'],$adata['pos_id'],$adata['num'],'-');
        }
    
    }
    
    /*
     * 备注：在途库存相关方法，可以删除此方法
    * \app\purchase\model\po.php 中使用
    */
    function change_arrive_store($branch_id, $product_id, $num, $type='+')
    {
        $now = time();
        $store = "";
        switch($type)
        {
            case "+":
                $store = "arrive_store=IFNULL(arrive_store,0)+".$num;
                break;
            case "-":
                $store = " arrive_store=IF((CAST(arrive_store AS SIGNED)-$num)>0,arrive_store-$num,0) ";
                break;
            case "=":
            default:
                $store = "arrive_store=".$num;
                break;
        }
        $branch_pro = $this->db->selectrow("SELECT arrive_store FROM sdb_ome_branch_product WHERE product_id=".$product_id." AND branch_id=".$branch_id."");
        if($branch_pro){
            $sql   = "UPDATE ".DB_PREFIX."ome_branch_product SET ".$store." WHERE product_id=".$product_id." AND branch_id=".$branch_id;
        }else{
            $sql = "INSERT INTO sdb_ome_branch_product(arrive_store,product_id,branch_id) VALUES('$num','$product_id','$branch_id')";
        }
        $rs    = $this->db->exec($sql);
    
        return $rs;
    }
    
    /*
     * 备注：货位相关方法，可以删除此方法
    * \app\purchase\controller\admin\stock.php
    */
    function Get_pos_id($branch_id,$store_position)
    {
        $obranch_pos = app::get('ome')->model('branch_pos');
    
        $pos    = $obranch_pos->dump(array('branch_id'=>$branch_id,'store_position'=>$store_position),'pos_id');
    
        return $pos['pos_id'];
    }
    
    /*
     * 获取货品在对应仓库中的库存
    *
    * @param int $product_id 货品id
    *
    * @return array
    */
    function get_branch_store($product_id)
    {
        $ret = array();
        $branch_product = $this->db->select("SELECT * FROM sdb_ome_branch_product WHERE product_id=".intval($product_id));
        
        if($branch_product)
        {
            foreach($branch_product as $v){
                //将订单确认拆分的仓库货品数量由store改为store_freeze
                $store = max(0,$v['store']-$v['store_freeze']);
                $ret[$v['branch_id']] = $store;
            }
        }
        return $ret;
    }
    
    /*
     * 根据仓库ID和货品ID 获取相应的库存数量
    *
    * @param int $product_id 货品id
    *
    * @return array
    */
    function get_product_store($branch_id, $product_id)
    {
        $sql    = "SELECT * FROM sdb_ome_branch_product WHERE product_id=".intval($product_id)." AND branch_id=".intval($branch_id);
        $branch_product = $this->db->selectrow($sql);
        $sale_store     = $branch_product['store'] - $branch_product['store_freeze'];
        
        return $sale_store;
    }
}
